import streamlit as st
import pandas as pd
from database_manager import DatabaseManager
import tempfile
import os
import time

def safe_delete_file(file_path: str, max_retries: int = 3):
    """安全删除文件，带有重试机制"""
    for _ in range(max_retries):
        try:
            if os.path.exists(file_path):
                os.unlink(file_path)
            return True
        except PermissionError:
            time.sleep(0.1)  # 等待一小段时间后重试
    return False

def render_admin_page():
    st.title("课程管理系统")
    
    # 初始化数据库管理器
    if 'db_manager' not in st.session_state:
        st.session_state.db_manager = DatabaseManager()
    
    # 创建两个标签页
    tab1, tab2 = st.tabs(["课程管理", "数据预处理"])
    
    with tab1:
        st.header("课程管理")
        
        # 文件上传
        uploaded_file = st.file_uploader("上传课程数据（CSV/JSON）", type=['csv', 'json'])
        if uploaded_file:
            file_type = uploaded_file.name.split('.')[-1]
            tmp_file_path = None
            try:
                with tempfile.NamedTemporaryFile(delete=False, suffix=f'.{file_type}') as tmp_file:
                    tmp_file.write(uploaded_file.getvalue())
                    tmp_file_path = tmp_file.name
                
                if st.button("导入数据"):
                    if st.session_state.db_manager.import_from_file(tmp_file_path, file_type):
                        st.success("数据导入成功！")
                    else:
                        st.error("数据导入失败，请检查文件格式。")
            finally:
                if tmp_file_path:
                    safe_delete_file(tmp_file_path)
        
        # 手动添加课程
        with st.expander("手动添加课程"):
            with st.form("add_course_form"):
                course_id = st.text_input("课程ID")
                name = st.text_input("课程名称")
                description = st.text_area("课程描述")
                grade_level = st.selectbox("适用年级", ["小学", "初中", "高中", "大学"])
                subject = st.text_input("学科分类")
                difficulty = st.selectbox("难度等级", ["入门", "基础", "进阶", "高级"])
                course_url = st.text_input("课程链接")
                
                if st.form_submit_button("添加课程"):
                    course_data = {
                        "course_id": course_id,
                        "name": name,
                        "description": description,
                        "grade_level": grade_level,
                        "subject": subject,
                        "difficulty": difficulty,
                        "course_url": course_url
                    }
                    if st.session_state.db_manager.add_course(course_data):
                        st.success("课程添加成功！")
                    else:
                        st.error("课程添加失败，请检查数据。")
        
        # 课程列表
        st.header("课程列表")
        page = st.number_input("页码", min_value=1, value=1)
        per_page = st.selectbox("每页显示数量", [5, 10, 20, 50])
        
        courses = st.session_state.db_manager.get_courses(page, per_page)
        if courses:
            df = pd.DataFrame(courses)
            st.dataframe(df)
            
            # 删除功能
            course_to_delete = st.text_input("输入要删除的课程ID")
            if st.button("删除课程"):
                if st.session_state.db_manager.delete_course(course_to_delete):
                    st.success("课程删除成功！")
                    st.rerun()
                else:
                    st.error("课程删除失败，请检查课程ID。")
        else:
            st.info("暂无课程数据")
    
    with tab2:
        st.header("数据预处理")
        
        # 数据清洗
        if st.button("执行数据清洗"):
            st.info("数据清洗功能将在后续版本中实现")
        
        # Embedding生成
        if st.button("生成Embedding"):
            st.info("Embedding生成功能将在后续版本中实现")
        
        # 数据持久化状态
        st.subheader("数据持久化状态")
        st.info("ChromaDB和SQLite数据库已就绪") 